#include <project.h>
#include "userMain.h"
#include "userUartRxCtrl.h"

circle_buffer userRxBuffer;
unsigned char userUartRxResetFlag = 0;
void userRxBufferPop(unsigned char* user_buf)
{
    *user_buf = userRxBuffer.circle_buffer[userRxBuffer.read_pos];    //如果缓冲区非空则取头节点值并偏移头节点
    if(++userRxBuffer.read_pos >= BUFFER_MAX)
         userRxBuffer.read_pos = 0;
}

void userGetRxBufferLen(unsigned char* user_RxLen)
{
    if(userUartRxResetFlag) 
    {
        *user_RxLen = 0;
        return ;
    }
    if(userRxBuffer.write_pos >= userRxBuffer.read_pos)
    {
        *user_RxLen = userRxBuffer.write_pos - userRxBuffer.read_pos;
    }
    else 
    {
        *user_RxLen = BUFFER_MAX - userRxBuffer.read_pos + userRxBuffer.write_pos;
    }
}

#define     UART_RX_IDLE    8
unsigned char uUartRxFinishMarkTick = 0;
void userUartRxFinishTick(void)
{
    if(uUartRxFinishMarkTick < 240)
     uUartRxFinishMarkTick++;
}

unsigned char userUartRxIdle(void)
{
    if(uUartRxFinishMarkTick < UART_RX_IDLE) 
        return 0;
    else
        return 1;
}

void userUartRxBufferPush(const unsigned char _buf)
{   
    uUartRxFinishMarkTick = 0;
    if(userUartRxResetFlag)
    {
        userRxBufferReset();
        userUartRxResetFlag = 0;
    }
    userRxBuffer.circle_buffer[userRxBuffer.write_pos]=_buf; //从尾部追加
    if(++userRxBuffer.write_pos>=BUFFER_MAX)           //尾节点偏移
        userRxBuffer.write_pos=0;                      //大于数组最大长度 制零 形成环形队列
}

void userRxMemcpy(unsigned char* dst_buf, unsigned char len)
{
    unsigned char user_i;
    if(len==0) return ;
    for(user_i=1;user_i<len;user_i++)
    {
        userRxBufferPop(dst_buf+user_i);
    }
    if(userRxBuffer.read_pos >= userRxBuffer.write_pos)
    {
       userUartRxResetFlag = 1;
    }
}
void userRxBufferReset(void)
{
    userUartRxResetFlag = 1;
    userRxBuffer.read_pos=0;
    userRxBuffer.write_pos=0;
    memset(userRxBuffer.circle_buffer,0,BUFFER_MAX);
}